<template>
	<view class="date-time-picker" v-if="visible">
		<view class="picker-mask" @tap="cancel"></view>
		<view class="picker-content">
			<view class="picker-header">
				<text class="cancel-btn" @tap="cancel">取消</text>
				<text class="type-switch">
					<!-- {{ currentType === 'start' ? '开始时间' : '结束时间' }} -->
					<text @tap="switchType">开始时间</text>
					<text @tap="switchType">结束时间</text>
				</text>
				<text class="confirm-btn" @tap="confirm">确定</text>
			</view>
			<picker-view class="picker-view" :value="currentPickerValue" @change="onChange">
				<picker-view-column>
					<view class="picker-item" v-for="year in years" :key="year">{{ year }}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="month in months" :key="month">{{ month }}月</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="day in days" :key="day">{{ day }}日</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="hour in hours" :key="hour">{{ hour }}时</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="minute in minutes" :key="minute">{{ minute }}分</view>
				</picker-view-column>
				<picker-view-column>
					<view class="picker-item" v-for="second in seconds" :key="second">{{ second }}秒</view>
				</picker-view-column>
			</picker-view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			initialStartDateTime: {
				type: String,
				default: null
			},
			initialEndDateTime: {
				type: String,
				default: null
			}
		},
		data() {
			return {
				currentType: 'start',
				startPickerValue: [],
				endPickerValue: [],
				years: [],
				months: [],
				days: [],
				hours: [],
				minutes: [],
				seconds: []
			};
		},
		computed: {
			currentPickerValue() {
				return this.currentType === 'start' ? this.startPickerValue : this.endPickerValue;
			},
			formattedStartDateTime() {
				return this.formatDateTime(this.startPickerValue);
			},
			formattedEndDateTime() {
				return this.formatDateTime(this.endPickerValue);
			}
		},
		watch: {
			visible(newValue) {
				if (newValue) {
					this.$nextTick(() => {
						this.initPickerValues();
					});
				}
			}
		},
		methods: {
			initPickerValues() {
				const currentDateTime = this.getCurrentDateTime();
				this.setCurrentDateTime(currentDateTime, 'start');
				this.setCurrentDateTime(this.getDefaultEndDateTime(), 'end');
			},

			initPickerValue(dateTimeString, type) {
				let [year, month, day, hour, minute, second] = this.parseDateTimeString(dateTimeString);

				this.years = this.generateYears();
				this.months = this.generateArray(1, 12);
				this.updateDays(year, month);
				this.hours = this.generateArray(0, 23);
				this.minutes = this.generateArray(0, 59);
				this.seconds = this.generateArray(0, 59);

				const pickerValue = [
					this.years.findIndex(y => y == year),
					month - 1,
					day - 1,
					hour,
					minute,
					second
				];

				if (type === 'start') {
					this.startPickerValue = pickerValue;
				} else {
					this.endPickerValue = pickerValue;
				}
			},
			parseDateTimeString(dateTimeString) {
				const [datePart, timePart] = dateTimeString.split(' ');
				const [year, month, day] = datePart.split('-').map(Number);
				const [hour, minute, second] = timePart.split(':').map(Number);
				return [year, month, day, hour, minute, second];
			},
			getCurrentDateTime() {
				const now = new Date();
				now.setHours(now.getHours() + 1);
				return this.formatDate(now);
			},

			getDefaultEndDateTime() {
				const now = new Date();
				now.setHours(now.getHours() + 36);
				return this.formatDate(now);
			},
			generateYears() {
				const currentYear = new Date().getFullYear();
				return this.generateArray(currentYear, currentYear + 10);
			},
			generateArray(start, end) {
				return Array.from({
					length: end - start + 1
				}, (_, i) => start + i);
			},
			updateDays(year, month) {
				const daysInMonth = new Date(year, month, 0).getDate();
				this.days = this.generateArray(1, daysInMonth);
			},
			onChange(e) {
				const values = e.detail.value;
				if (this.currentType == 'start') {
					this.startPickerValue = values;
				} else {
					this.endPickerValue = values;
				}
				this.validateAndAdjustTime();
			},
			validateAndAdjustTime() {
				const startDate = this.getDateFromPickerValue(this.startPickerValue);
				const endDate = this.getDateFromPickerValue(this.endPickerValue);
				const now = new Date();

				if (startDate < now) {
					this.setCurrentDateTime(this.formatDate(now), 'start');
					this.$u.toast('开始时间不能早于当前时间');
				}

				if (endDate <= startDate) {
					const newEndDate = new Date(startDate.getTime() + 60 * 60 * 1000);
					this.setCurrentDateTime(this.formatDate(newEndDate), 'end');
					this.$u.toast('结束时间不能早于开始时间');
				}
			},
			getDateFromPickerValue(pickerValue) {
				const [yearIndex, monthIndex, dayIndex, hour, minute, second] = pickerValue;
				return new Date(
					this.years[yearIndex],
					monthIndex,
					this.days[dayIndex],
					hour,
					minute,
					second
				);
			},
			formatDate(date) {
				return `${date.getFullYear()}-${this.pad(date.getMonth() + 1)}-${this.pad(date.getDate())} ${this.pad(date.getHours())}:${this.pad(date.getMinutes())}:${this.pad(date.getSeconds())}`;
			},
			pad(num) {
				return num < 10 ? `0${num}` : num;
			},
			setCurrentDateTime(dateTimeString, type) {
				let [year, month, day, hour, minute, second] = this.parseDateTimeString(dateTimeString);

				this.years = this.generateYears();
				this.months = this.generateArray(1, 12);
				this.updateDays(year, month);
				this.hours = this.generateArray(0, 23);
				this.minutes = this.generateArray(0, 59);
				this.seconds = this.generateArray(0, 59);

				const pickerValue = [
					this.years.findIndex(y => y == year),
					month - 1,
					day - 1,
					hour,
					minute,
					second
				];

				if (type === 'start') {
					this.startPickerValue = pickerValue;
				} else {
					this.endPickerValue = pickerValue;
				}
			},
			formatDateTime(pickerValue) {
				const [yearIndex, monthIndex, dayIndex, hour, minute, second] = pickerValue;
				const year = this.years[yearIndex];
				const month = this.pad(this.months[monthIndex]);
				const day = this.pad(this.days[dayIndex]);
				return `${year}-${month}-${day} ${this.pad(hour)}:${this.pad(minute)}:${this.pad(second)}`;
			},
			pad(num) {
				return num < 10 ? `0${num}` : num;
			},
			switchType() {
				this.currentType = this.currentType === 'start' ? 'end' : 'start';
			},
			confirm() {
				this.$emit('confirm', {
					startDateTime: this.formattedStartDateTime,
					endDateTime: this.formattedEndDateTime
				});
			},
			cancel() {
				this.$emit('cancel');
			}
		}
	};
</script>

<style scoped lang="scss">
	.date-time-picker {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 99999;
	}

	.picker-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
	}

	.picker-content {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #d3edf8;
	}

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		border-bottom: 1px solid #eee;
	}

	.cancel-btn,
	.confirm-btn,
	.type-switch {
		padding: 5px 10px;
	}

	.type-switch {
		font-weight: bold;

		text {
			display: inline-block;
			margin: 20rpx;
		}
	}

	.picker-view {
		height: 350px;
	}

	.picker-item {
		line-height: 34px;
		text-align: center;
	}
</style>